from src.choice_api.utils import data_str2timestamp, sort_by_first_element


def parse_drug_inventory(data, columns):
    if data is None or "list" not in data:
        return None

    data_lst = data["list"]
    if not data_lst:
        data_lst = []

    # 真实要获取的字段
    columns_lst_mapping = {
        "出库/入库数量": "num",
        "库存总量(变化)": "inventory",
    }
    columns_means = list(columns_lst_mapping.keys())
    columns_lst = list(columns_lst_mapping.values())

    # target_columns = extract_columns_callback(columns_means)
    # target_correct_columns = []
    # if target_columns and len(target_columns) != 0:
    #     for target_column in target_columns:
    #         if target_column in columns_means:
    #             target_correct_columns.append(columns_lst_mapping[target_column])
    #     if len(target_correct_columns) > 0:
    #         columns_lst = target_correct_columns

    # 单表csv解析
    # res_columns = ["time"]
    # res_data = [[x["time"]] for x in company_lst[list(company_lst.keys())[0]]]
    #
    # for k, val_lst in company_lst.items():
    #     for param in columns_lst:
    #         res_columns.append(f"{k} {param_mapping[param]}")
    #         for idx, val in enumerate(val_lst):
    #             res_data[idx].append(val[param])
    # return {
    #     "res_columns": res_columns,
    #     "res_data": res_data,
    # }

    type_mapping = {1: '入库', 2: '出库'}

    # 单表时序指标形式
    res_columns = []
    res_data = {}
    res_tip = []

    for row in data_lst:
        if "num" in columns_lst:
            if row["type"] == 1:
                tip = f"{row["name"]}入库{row["num"]}{row["unit"]}：送货商【{row["deliverer"]}】,验收人【{row["acceptor"]}】,送货日期【{row["recordTime"]}】"
                res_tip.append(tip)

            label = f"药剂{type_mapping[row["type"]]} {row["name"]}"
            if label not in res_columns:
                res_columns.append(label)
                res_data[label] = []

            res_data[label].append([data_str2timestamp(row["recordTime"]), row["num"]])

        if "inventory" in columns_lst:
            label = f"药剂库存 {row["name"]}"
            if label not in res_columns:
                res_columns.append(label)
                res_data[label] = []

            res_data[label].append([data_str2timestamp(row["recordTime"]), row["inventory"]])



    for column in res_columns:
        res_data[column] = sort_by_first_element(res_data[column])

    return {
        "res_columns": res_columns,
        "res_data": res_data,
        "res_tip": res_tip
    }
